package elements.axis; 
import flash.display.Sprite;
import flash.geom.Point;
import string.Utils;
import elements.Types.Style;

class RadarAxis extends Sprite {
	var style:Style;
	var TO_RADIANS:Int ;
	
	var colour:String;
	var grid_colour:String;
	var labels:RadarAxisLabels;
	var spoke_labels:RadarSpokeLabels;
	
	function new( json:Dynamic )
	{
		super();
		// default values
		
		TO_RADIANS = Math.PI / 180;
		this.style = {
			stroke:			2,
			colour:			'#784016',
			grid_colour:		'#F5E1AA',
			min:			0,
			max:			null,
			steps:			1
		};
		
		if( json != null )
			Object_helper.merge_2( json, this.style );
			
		this.colour = Utils.get_colour( this.style.colour );
		this.grid_colour = Utils.get_colour( this.style['grid-colour'] );
		
		this.labels = new RadarAxisLabels( json.labels );
		this.addChild( this.labels );
		
		this.spoke_labels = new RadarSpokeLabels( json['spoke-labels'] );
		this.addChild( this.spoke_labels );
	}
	
	//
	// how many items in the X axis?
	//
	public function get_range():Range {
		return new Range( this.style.min, this.style.max, this.style.steps, false );
	}
	
	public function resize( sc:ScreenCoordsRadar ):Void
	{
		this.x = 0;
		this.y = 0;
		this.graphics.clear();
		
		// this is going to change the radius
		this.spoke_labels.resize( sc );
		
		var count:Int = sc.get_angles();
		
		// draw the grid behind the axis
		this.draw_grid( sc, count );
		this.draw_axis( sc, count );
		
		this.labels.resize( sc );
	}
	
	function draw_axis( sc:ScreenCoordsRadar, count:Float ): Void {
		
		this.graphics.lineStyle(this.style.stroke, this.colour, 1, true);
		
		for ( i in 0...count) {

			//
			// assume 0 is MIN
			//
			var p:flash.geom.Point = sc.get_get_x_from_pos_and_y_from_val( i, 0 );
			this.graphics.moveTo( p.x, p.y );
			
			var q:flash.geom.Point = sc.get_get_x_from_pos_and_y_from_val( i, sc.get_max() );
			this.graphics.lineTo( q.x, q.y );
		}
	}
	
	function draw_grid( sc:ScreenCoordsRadar, count:Float ):Void {
	
		this.graphics.lineStyle(1, this.grid_colour, 1, true);
		
		// floating Point addition error:
		var max:Float = sc.get_max() + 0.00001;
		
		var r_step:Int = this.style.steps;
		var p:flash.geom.Point;
		
		//
		// start in the middle and move out drawing the grid,
		// don't draw at 0
		//
		var r_pos:Int = r_step;
			
		while ( r_pos <= max) {
			
			p = sc.get_get_x_from_pos_and_y_from_val( 0, r_pos );
			this.graphics.moveTo( p.x, p.y );
			
			// draw from each spoke
			for ( i in 1...(count+1)) {
				
				p = sc.get_get_x_from_pos_and_y_from_val( i, r_pos );
				this.graphics.lineTo( p.x, p.y );
			}
			r_pos+=r_step ;
			
		}
	}
	
	public function die(): Void {
		
		this.style = null;
		this.labels.die();
		this.spoke_labels.die();
	
		this.graphics.clear();
		while ( this.numChildren > 0 )
			this.removeChildAt(0);
	}
}
